package com.example.demo3.controller;

import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo3.domain.User;

/**
 * User: wangy
 * Date: 2020/5/15
 * Description: No Description
 */
@Controller
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private JwtUtils jwtUtils;
    
    @RequestMapping("/login")
    public String toLogin(){
        return "login";
    }

    
    @RequestMapping("/doLogin")
    public String doLogin(String username,String password,Model model) throws NoSuchAlgorithmException{
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                username,
                password);
        //进行验证，这里可以捕获异常，然后返回对应信息
        //默认登陆成功后跳转的是刚才访问的页面
        try {
            subject.login(usernamePasswordToken);
            if (subject.isAuthenticated()){
            	String jwtToken = jwtUtils.generateToken(username, UUID.randomUUID().toString());
            	System.out.println(jwtToken);
                return "redirect:/index";
            }else{
                usernamePasswordToken.clear();
                return "redirect:/login";
            }
        }catch (UnknownAccountException e){
          model.addAttribute("msg","用户名不存在");
          return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }

    @RequestMapping("/index")
    public String toIndex(Model model){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        model.addAttribute("user",user);
        return "index";
    }

    @RequestMapping("/logout")
    public String doLogOut(Model model){
     Subject subject = SecurityUtils.getSubject();
     subject.logout();
     model.addAttribute("msg", "安全退出!");
     return "login";
    }
    
    /**
     * 密码生成
     * 
     * @param args
     */
    public static void main(String[] args) {
		String hashAlgorithmName="MD5";
		Object credentials="admin";
		Object salt="7mrNoL/keN6rbqZDx+PKyg==";
		int hashIterations=2;
		Object result=new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		System.out.println(result);
	}
}
